package cn.yunhe.test;

import cn.yunhe.entity.Course;
import cn.yunhe.entity.Jd;
import cn.yunhe.entity.Qx;
import cn.yunhe.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Iterator;

public class Demo1 {
    Session session = null;
    Transaction tr = null;

    @Before
    public void init() {
        Configuration config=new Configuration().configure();
        SessionFactory sf = config.buildSessionFactory();
        session = sf.openSession();
        //saveManyAndOne可以用到
        tr=session.beginTransaction();

    }

    @Test
    public void manyToOne() {
        Jd jd = (Jd) session.get(Jd.class, 1);
        System.out.println("街道" + jd.getJdname() + "所属的区县为" + jd.getQx().getQxname());

    }

    @Test
    public void ontToMany() {
        Qx qx = (Qx) session.get(Qx.class, 4);
        System.out.println("区县：" + qx.getQxname() + "下面的街道：");
        //迭代器
        Iterator<Jd> jds = qx.getJds().iterator();
        while (jds.hasNext()) {
            System.out.println(jds.next().getJdname());
        }
    }

    @Test
    public void saveManyAndOne() {
        Jd jd1 = new Jd();
        jd1.setJdname("人民路");
        Jd jd2 = new Jd();
        jd2.setJdname("黄河路");
        Jd jd3 = new Jd();
        jd3.setJdname("青年路");
        session.save(jd1);
        session.save(jd2);
        session.save(jd3);
        Qx qx=new Qx();
        qx.setQxname("郑州区");
        qx.getJds().add(jd1);
        qx.getJds().add(jd2);
        qx.getJds().add(jd3);
        session.save(qx);
    }

    @Test
    //删除多的一方
    public void delMany(){
       Jd jd= (Jd) session.get(Jd.class,2);
       Qx qx= (Qx) session.get(Qx.class,2);
       qx.getJds().remove(jd);
       session.delete(jd);
    }

@Test
    //删除一的一方，配置文件中 set里 cascade="all"
    public void delOne(){
       Qx qx= (Qx) session.get(Qx.class,8);
       session.delete(qx);
    }
@Test
    public void manyToMany(){
        Course course1=new Course();
        Course course2=new Course();
        course1.setCoursename("java");
        course2.setCoursename(".net");
        session.save(course1);
        session.save(course2);
        Student stu1=new Student();
        Student stu2=new Student();
        stu1.setStuname("张三0");
        stu2.setStuname("李四");
        stu1.getCourses().add(course1);
        stu1.getCourses().add(course2);
        stu2.getCourses().add(course1);
        stu2.getCourses().add(course2);
        session.save(stu1);
        session.save(stu2);
    }
    @After
    public void des() {
        tr.commit();
        session.close();
    }
}
